/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Home.java
 *
 * Created on 21/05/2012, 00:40:23
 */
package trabalho1.GUI;

import java.util.Enumeration;
import trabalho1.AcessoArquivo.acessoArquivoException;
import java.awt.Cursor;
import java.awt.HeadlessException;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import trabalho1.AcessoArquivo.AcessoArquivoAPP;
import trabalho1.ObjetosNegocio.Comissao;
import trabalho1.RegrasCalculo.CalculoComissaoAPP;

/**
 *
 * @author Amandaa
 */
public class Home extends javax.swing.JFrame {
    public static final String SELECAO_ARQUIVO_XML = "Arquivo XML";
    public static final String SELECAO_PONTO_E_VIRGULA = "Arquivo separado por ponto e v\u00edrgula";
    private static final String ARQUIVO_DE_PRECOS_NAO_ENCONTRADO = "Arquivo de Pre\u00e7os N\u00e3o Encontrado";
    private static final String ARQUIVO_DE_VENDEDORES_NAO_ENCONTRADO = "Arquivo de Vendedores N\u00e3o Encontrado";
    private static final String JFILECHOOSER_APPROVE_BUTTON = "Selecionar";
    private static final String MSG_ARQUIVO_DE_VENDAS_NAO_ENCONTRADO = "Arquivo de Vendas N\u00e3o Encontrado";
    private static final String TITULO_JFILECHOOSER_PRECO = "Selecionar Arquivo Pre\u00e7o";
    private static final String TITULO_JFILECHOOSER_VENDA = "Selecionar Arquivo Venda";
    private static final String TITULO_JFILECHOOSER_VENDEDOR = "Selecionar Arquivo Vendedor";

    /** Creates new form Home */
    public Home() {
        initComponents();
    }

    private boolean abrirJFileChooser(String tituloFileChooser) throws HeadlessException {
        jFileChooser1.setDialogTitle(tituloFileChooser);
        jFileChooser1.setApproveButtonText(JFILECHOOSER_APPROVE_BUTTON);
        jFileChooser1.showDialog(jPanel1, null);
        if (jFileChooser1.getSelectedFile() == null) {
            return true;
        }
        return false;
    }

    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        buttonGroupTipoArquivo = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        lblMes = new javax.swing.JLabel();
        lblVenda = new javax.swing.JLabel();
        lblPreco = new javax.swing.JLabel();
        lblVendedor = new javax.swing.JLabel();
        lblComissao = new javax.swing.JLabel();
        lblTitulo = new javax.swing.JLabel();
        txtVenda = new javax.swing.JTextField();
        txtPreco = new javax.swing.JTextField();
        txtVendedor = new javax.swing.JTextField();
        txtComissao = new javax.swing.JTextField();
        btnCalcular = new javax.swing.JButton();
        jComboBoxMes = new javax.swing.JComboBox();
        jButtonSelecionarVenda = new javax.swing.JButton();
        jButtonSelecionarPreco = new javax.swing.JButton();
        jButtonSelecionarVendedor = new javax.swing.JButton();
        jRadioButtonArquivoXML = new javax.swing.JRadioButton();
        jRadioButtonArquivoPontoVirgula = new javax.swing.JRadioButton();
        jLabelTipoArquivo = new javax.swing.JLabel();

        jFileChooser1.setPreferredSize(new java.awt.Dimension(647, 450));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cálculo de Comissões");

        jPanel1.setBackground(new java.awt.Color(102, 102, 102));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        lblMes.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblMes.setForeground(new java.awt.Color(255, 255, 255));
        lblMes.setText("Mês:");

        lblVenda.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblVenda.setForeground(new java.awt.Color(255, 255, 255));
        lblVenda.setText("Nome arquivo Venda:");

        lblPreco.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblPreco.setForeground(new java.awt.Color(255, 255, 255));
        lblPreco.setText("Nome arquivo Preco:");

        lblVendedor.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblVendedor.setForeground(new java.awt.Color(255, 255, 255));
        lblVendedor.setText("Nome arquivo Vendedor:");

        lblComissao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblComissao.setForeground(new java.awt.Color(255, 255, 255));
        lblComissao.setText("Nome arquivo Comissão:");

        lblTitulo.setFont(new java.awt.Font("Tahoma", 0, 18));
        lblTitulo.setForeground(new java.awt.Color(255, 255, 255));
        lblTitulo.setText("Cálculo de Comissões");

        btnCalcular.setFont(new java.awt.Font("Tahoma", 0, 12));
        btnCalcular.setText("Calcular");
        btnCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCalcularActionPerformed(evt);
            }
        });

        jComboBoxMes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }));

        jButtonSelecionarVenda.setText("Selecionar...");
        jButtonSelecionarVenda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelecionarVendaActionPerformed(evt);
            }
        });

        jButtonSelecionarPreco.setText("Selecionar...");
        jButtonSelecionarPreco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelecionarPrecoActionPerformed(evt);
            }
        });

        jButtonSelecionarVendedor.setText("Selecionar...");
        jButtonSelecionarVendedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelecionarVendedorActionPerformed(evt);
            }
        });

        jRadioButtonArquivoXML.setBackground(new java.awt.Color(102, 102, 102));
        buttonGroupTipoArquivo.add(jRadioButtonArquivoXML);
        jRadioButtonArquivoXML.setForeground(new java.awt.Color(255, 255, 255));
        jRadioButtonArquivoXML.setText(SELECAO_ARQUIVO_XML);

        jRadioButtonArquivoPontoVirgula.setBackground(new java.awt.Color(102, 102, 102));
        buttonGroupTipoArquivo.add(jRadioButtonArquivoPontoVirgula);
        jRadioButtonArquivoPontoVirgula.setForeground(new java.awt.Color(255, 255, 255));
        jRadioButtonArquivoPontoVirgula.setText(SELECAO_PONTO_E_VIRGULA);

        jLabelTipoArquivo.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabelTipoArquivo.setForeground(new java.awt.Color(255, 255, 255));
        jLabelTipoArquivo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelTipoArquivo.setText("Esolha o tipo de arquivo");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(171, 171, 171)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(jLabelTipoArquivo)
                            .addComponent(lblTitulo)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(125, 125, 125)
                        .addComponent(jRadioButtonArquivoXML)
                        .addGap(18, 18, 18)
                        .addComponent(jRadioButtonArquivoPontoVirgula))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(148, 148, 148)
                        .addComponent(btnCalcular, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblMes, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblVenda, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblPreco, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblVendedor, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblComissao, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(3, 3, 3)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtPreco, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtComissao, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonSelecionarVenda)
                            .addComponent(jButtonSelecionarPreco)
                            .addComponent(jButtonSelecionarVendedor))))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(lblTitulo)
                .addGap(18, 18, 18)
                .addComponent(jLabelTipoArquivo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButtonArquivoXML)
                    .addComponent(jRadioButtonArquivoPontoVirgula))
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jComboBoxMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMes))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(lblVenda)
                    .addComponent(txtVenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSelecionarVenda))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(txtPreco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSelecionarPreco)
                    .addComponent(lblPreco))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(lblVendedor)
                    .addComponent(txtVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSelecionarVendedor))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(lblComissao)
                    .addComponent(txtComissao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnCalcular)
                .addGap(51, 51, 51))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalcularActionPerformed
        int mes = Integer.parseInt((String)jComboBoxMes.getSelectedItem());
        String arqVendas = txtVenda.getText();         
        String arqPrecos = txtPreco.getText();         
        String arqVendedores = txtVendedor.getText();         
        String arqComissao = txtComissao.getText();

        Map<String, Comissao> comissoes = new HashMap<String, Comissao>();        
        String tipoAcessoArquivo = null;
        
        if(!arquivosExistem(arqVendas, arqPrecos, arqVendedores))
            return;
        if((tipoAcessoArquivo = getSelectionText(buttonGroupTipoArquivo)) == null)
            return;

        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        try {
            try{
                CalculoComissaoAPP calculoComissoes = new CalculoComissaoAPP();
                comissoes = calculoComissoes.ativarGerarComissoes(mes, arqVendas, arqPrecos, arqVendedores,
                                                                  arqComissao, tipoAcessoArquivo);

                
                AcessoArquivoAPP accArqComissao = new AcessoArquivoAPP();
                accArqComissao.ativarEscreverComissao(comissoes, arqComissao, tipoAcessoArquivo);

                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                MostraMensagemSucesso();
            } finally {
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            }
        } catch (acessoArquivoException ex) {             
            MostraMensagemErro(ex.getMessage());         
        }
        
    }//GEN-LAST:event_btnCalcularActionPerformed

    private void jButtonSelecionarVendaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelecionarVendaActionPerformed

        if(abrirJFileChooser((TITULO_JFILECHOOSER_VENDA)))
            return;
        
        txtVenda.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
    }//GEN-LAST:event_jButtonSelecionarVendaActionPerformed

    private void jButtonSelecionarPrecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelecionarPrecoActionPerformed
        
        if(abrirJFileChooser(TITULO_JFILECHOOSER_PRECO))
            return;
        
        txtPreco.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
    }//GEN-LAST:event_jButtonSelecionarPrecoActionPerformed

    private void jButtonSelecionarVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelecionarVendedorActionPerformed

        if(abrirJFileChooser(TITULO_JFILECHOOSER_VENDEDOR))
            return;
        
        txtVendedor.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
    }//GEN-LAST:event_jButtonSelecionarVendedorActionPerformed

    //Este método retorna o texto do radio button selecionado em um button group.
    public String getSelectionText(ButtonGroup group) {
        for (Enumeration e=group.getElements(); e.hasMoreElements(); ) {
            JRadioButton b = (JRadioButton)e.nextElement();
            if (b.getModel() == group.getSelection()) {
                return b.getText();
            }
        }
        
        MostraMensagemErro("Escolha um tipo de arquivo");
        return null;
    }

    public void MostraMensagemSucesso() {
        JOptionPane.showMessageDialog(this, "Comissão gerada com sucesso!", "Sucesso",JOptionPane.INFORMATION_MESSAGE);
    }

    public void MostraMensagemErro(String message){
        JOptionPane.showMessageDialog(this, "Erro: " + message, "Erro", JOptionPane.ERROR_MESSAGE);
    }
    
    public boolean arquivosExistem(String arqVendas, String arqPrecos, String arqVendedores) throws HeadlessException {
        if(!(new File(arqVendas).exists())){
            MostraMensagemErro(MSG_ARQUIVO_DE_VENDAS_NAO_ENCONTRADO);
            return false;
        }
        else if(!(new File(arqPrecos).exists())){
            MostraMensagemErro(ARQUIVO_DE_PRECOS_NAO_ENCONTRADO);
            return false;
        }
        else if(!(new File(arqVendedores).exists())){
            MostraMensagemErro(ARQUIVO_DE_VENDEDORES_NAO_ENCONTRADO);
            return false;
        }
        return true;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Home().setVisible(true);
            }
        });
    }
    
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCalcular;
    private javax.swing.ButtonGroup buttonGroupTipoArquivo;
    private javax.swing.JButton jButtonSelecionarPreco;
    private javax.swing.JButton jButtonSelecionarVenda;
    private javax.swing.JButton jButtonSelecionarVendedor;
    private javax.swing.JComboBox jComboBoxMes;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabelTipoArquivo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButtonArquivoPontoVirgula;
    private javax.swing.JRadioButton jRadioButtonArquivoXML;
    private javax.swing.JLabel lblComissao;
    private javax.swing.JLabel lblMes;
    private javax.swing.JLabel lblPreco;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JLabel lblVenda;
    private javax.swing.JLabel lblVendedor;
    private javax.swing.JTextField txtComissao;
    private javax.swing.JTextField txtPreco;
    private javax.swing.JTextField txtVenda;
    private javax.swing.JTextField txtVendedor;
    // End of variables declaration//GEN-END:variables
}
